package demo.server.controller;

import java.util.concurrent.atomic.AtomicInteger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import com.google.protobuf.GeneratedMessage.GeneratedExtension;
import demo.TestMessageId;
import demo.protocol.MessageTestProto;
import demo.protocol.MessageTestProto.Request;
import net.jueb.protoServer.boot.ProtoServer;
import net.jueb.protoServer.controller.ProtoMessageController;
import net.jueb.protoServer.message.ProtoMessage;
import net.jueb.protoServer.message.ProtoMessage.Message;

public class MessageTestController extends ProtoMessageController<MessageTestProto.Request>{

	protected static final InternalLogger log = InternalLoggerFactory.getInstance(ProtoServer.class);
	@Override
	public String getControllerName() {
		
		return "测试扩展消息处理控制器";
	}

	@Override
	public int getId() {
		return TestMessageId.Request;
	}


	@Override
	public GeneratedExtension<Message, Request> getGeneratedExtension() {
		return MessageTestProto.request;
	}
	public AtomicInteger count=new AtomicInteger(0);
	
	@Override
	public void execute(ChannelHandlerContext ctx, Request extMsg) {
		//如果收到一次消息则建立线程,当收到10个报告就通知客户端
		log.info("ServerTime="+System.currentTimeMillis()+"时,服务端收到请求:"+extMsg.getInfo());
		count.addAndGet(1);
		MessageTestProto.Response.Builder b=MessageTestProto.Response.newBuilder();
		b.setInfo("收到第"+count.get()+"次消息了"+"ServerRecivedTime:"+System.currentTimeMillis()+",remoteAddress:"+ctx.channel().remoteAddress().toString());
		ProtoMessage.Message.Builder mRb=ProtoMessage.Message.newBuilder();
		mRb.setMsgId(TestMessageId.Response);
		mRb.setExtension(MessageTestProto.response, b.build());
		ProtoMessage.Message message=mRb.build();
		ctx.writeAndFlush(message);
	}


}
